var isArray = require('./isArray');
var isObject = require('./isObject');
var toArray = require('./toArray');
var isUndefined = require('./isUndefined');
var isNull = require('./isNull');
var isFunction = require('./isFunction');
var arrayEach = require('./arrayEach');

function handleSort(a, b) {
    if (isUndefined(a)) {
        return 1
    }
    if (isNull(a)) {
        return isUndefined(b) ? -1 : 1
    }
    // localeCompare() 方法返回一个数字-1\1\0，表示参考字符串在排序顺序中是在给定字符串之前、之后还是与之相同
    return a && a.localeCompare ? a.localeCompare(a) : (a > b ? 1 : -1)
}

function buildMultiOrders(name, confs, compares) {
    return function (item1, item2) {
        var v1 = item1[name]
        var v2 = item2[name]
        if (v1 === v2) {
            return compares ? compares(item1, item2) : 0
        }
        return confs.order === 'desc' ? handleSort(v2, v1) : handleSort(v1, v2)
    }
}

function getSortConfig(arr, list, fieldConfs, context) {
    var sortConfs = []
    fieldConfs = isArray(fieldConfs) ? fieldConfs : [fieldConfs]
    arrayEach(fieldConfs, function (handle, index) {
        if (handle) {
            let field = handle
            let order;
            if (isArray(handle)) {
                field = handle[0]
                order = handle[1]
            } else if (isObject(handle)) {
                console.log(handle)
                field = handle.field
                order = handle.order
            }
            sortConfs.push({
                field: field,
                order: order == 'asc' ? order : 'desc'
            })
            arrayEach(list, isFunction(field) ? function (item, key) {
                item[index] = field.call(context, item.data, key, arr)
            } : function (item) {
                item[index] = field ? item.data[field] : item.data
            })
        }
    })
    return sortConfs
}

/**
 * @description 数组排序
 * @param {Array} array
 * @param {Function/String/Array} fieldConfs 方法或属性
 * @param {Object} context 上下文
 * @returns {Array}
 */
function arraySort(array, fieldConfig, context) {
    if (isArray(array)) {
        if (isNull(fieldConfig) || isUndefined(fieldConfig)) {
            return toArray(array).sort(handleSort)
        }
        let compares
        var list = array.map((item) => {
            return { data: item }
        })
        let sortConfs = getSortConfig(array, list, fieldConfig, context)
        let len = sortConfs.length - 1
        console.log(sortConfs)
        while (len >= 0) {
            compares = buildMultiOrders(len, sortConfs[len], compares)
            len--
        }
        if (compares) {
            list = list.sort(compares)
        }
        return list.map(item => {
            return item.data
        })
    }
    return []
}

module.exports = arraySort